package main

import (
	"github.com/veandco/go-sdl2/img"
	"github.com/veandco/go-sdl2/sdl"
)

type Texture struct {
	*sdl.Texture
}

func (t *Texture) LoadFromFile(path string) bool {
	img, err := img.Load(path)
	if err != nil {
		panic(err)
	}
	t.Texture, err = Grender.CreateTextureFromSurface(img)
	if err != nil {
		panic(err)
	}
	img.Free()

	return true
}

func (t *Texture) Render(x, y int32, src *sdl.Rect) {
	dst := &sdl.Rect{X: x, Y: y, W: src.W, H: src.H}
	Grender.Copy(t.Texture, src, dst)
}

func (t *Texture) setColor(r, g, b uint8) {
	t.SetColorMod(r, g, b)
}

func (t *Texture) Free() {
	t.Texture.Destroy()
}

const (
	W = 670
	H = 620
)

var (
	Gwindow  *sdl.Window
	Grender  *sdl.Renderer
	Gtexture *Texture
)

func init() {
	sdl.Init(sdl.INIT_EVERYTHING)
	Gwindow, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, W, H, sdl.WINDOW_SHOWN)
	if err != nil {
		panic(err)
	}
	Grender, err = sdl.CreateRenderer(Gwindow, -1, sdl.RENDERER_ACCELERATED)
	if err != nil {
		panic(err)
	}
	Grender.SetDrawColor(128, 128, 128, 255)
	Gtexture = &Texture{}
	Gtexture.LoadFromFile("../asserts/image/texture.png")
}

func main() {
	sprit := &sdl.Rect{707, 3, 26, 26}

	r := uint8(255)
	g := uint8(255)
	b := uint8(255)

	running := true
	for running {
		for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
			switch t := event.(type) {
			case *sdl.QuitEvent:
				println("Quit")
				running = false
				break
			case *sdl.KeyboardEvent:
				switch t.Keysym.Sym {
				case sdl.K_q:
					r += 32
				case sdl.K_w:
					g += 32
				case sdl.K_e:
					b += 32
				case sdl.K_a:
					r -= 32
				case sdl.K_s:
					g -= 32
				case sdl.K_d:
					b -= 32
				}
			}
		}
		Grender.Clear()
		Gtexture.SetColorMod(r, g, b)
		Gtexture.Render(0, 0, sprit)

		Grender.Present()
		sdl.Delay(16)
	}
	free()
}

func free() {
	Gtexture.Destroy()
	Grender.Destroy()
	Gwindow.Destroy()
	sdl.Quit()
}
